//
//  MTOAuthViewController.swift
//  MTWeiBo
//
//  Created by user on 2017/7/24.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

//  新浪微博表示应用的唯一id
let Appkey = "953519347"
//  授权成功回调地址
let Redirect_uri = "http://www.baidu.com"

let client_secret = "d5f8898808174c63e9a01026190ec62c"

class MTOAuthViewController: UIViewController {
   
    //懒加载控件
    private lazy var webView = UIWebView()
    //重写loadview
    override func loadView() {
        webView.delegate = self
        view = webView
    }
       
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        setupNav()
        
        loadLogin()
        
    }
    
    //第三方登录
    private func loadLogin() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(Appkey)&redirect_uri=\(Redirect_uri)"
        let url = URL(string: urlStr)
        
        webView.loadRequest(URLRequest(url: url!))
        
    }

    //设置导航栏
    private func setupNav() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        
    }
    
    @objc private func cancelAction() {
        //返回上层
        self.dismiss(animated: true, completion: nil)
    }
    @objc private func autoFillAction() {
    
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '18861199331';document.getElementById('passwd').value = '1075036748';document.getElementById('passwd').focus();")
    }
    
    
//    //通过code(授权码)获取令牌（accessToken）
//    func requestAccessToken(code: String) {
//        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
//            if error != nil {
//                print("error: \(error!)")
//                return
//            }
//            //执行到此说明请求成功
//            //转成对应的字典类型
//            let dict = response as! [String: Any]
//            //字典转模型
//            let userAccount = MTUserAccount(dict: dict)
//            print(userAccount)
//            
//            //获取用户信息
//            self.requestUserInfo(userAccount: userAccount)
//        }
//    }
//    
//    //获取用户信息
//    private func requestUserInfo(userAccount: MTUserAccount) {
//        //令牌
//        let token = userAccount.access_token!
//        //uid
//        let uid = userAccount.uid
//        HMNetworkTools.sharedTools.requestUserInfo(access_token: token, uid: uid) { (response, error) in
//            if error != nil {
//                print("error: \(error!)")
//                return
//            }
//            //执行到此说明请求成功
//            //转成对应的字典
//            let dict = response as! [String: Any]
//            //给对象属性赋值
//            userAccount.name = dict["name"] as? String
//            userAccount.avatar_large = dict["avatar_large"] as? String
//            //print(userAccount.name)
//            //登录成功,保存用户对象
//            userAccount.saveUserAccount()
//        }
//        
//    }
    
}


extension MTOAuthViewController:UIWebViewDelegate {
    
    //将要加载网络请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.url?.absoluteString.hasPrefix(Redirect_uri) == true {
            //代码执行到此表示是以授权回调地址开头
            //query表示URL?后面的参数
            if let query = request.url?.query, query.hasPrefix("code="){
                //表示是我们需要的授权码参数
                //截取授权码参数
                let code = query.substring(from: "code=".endIndex)
                //print(code)
                //requestAccessToken(code: code)
                MTUserAccountViewModel.shardViewModel.requestAccessToken(code: code, callBack: { (isSuccess) in
                    if isSuccess {
                        //登录成功
                        print("登录成功")
                       // print(MTUserAccountViewModel.shardViewModel.userAccount?.name ?? 0)
                        //注意点： 需要让当前OAuthVCdismis完成以后再去切换根视图控制器，否则MainVC没有释放
                        self.dismiss(animated: false, completion: {
                            NotificationCenter.default.post(name:NSNotification.Name(rawValue: SwitchRootVCNotificationName), object: self)
                        })
                        
                    }else{
                        print("登录失败")
                    }
                })
            }else{
                //取消授权
                self.dismiss(animated: true, completion: nil)
            }
            return false
         
        }
        
        return true
    }
    
    //  已经开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        //  如果是false会执行加载失败的方法
        SVProgressHUD.dismiss()
    }

    
}


